(function ($) {
	var pageType="",userPicker;
	var perInfo=""
	var nurseid="",wardID = '',sourceData;
	var loginPerID=""
	$.init();
	$.plusReady(function() {
		baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	function saveOrCommit(){
		var tip = '保存'
		var status = 'N' //状态 N:保存 S:提交 A:审核 B:驳回
		if (this.id == 'commitBtn') {
			status = 'S'
			tip = '提交'
		}
		var parrDict = getSaveParams(status)
		if (parrDict == 0) {
			return
		}
		var pdict = {'parr':parrDict['parr']}
		if (parrDict['nurseid']) {
			pdict['nurseid'] = parrDict['nurseid']
		}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':parrDict['method'],'params':JSON.stringify(pdict),'type':'Method'}
		$.DHCWebService(paramDict, function(result) {
			console.log(JSON.stringify(result))
			plus.nativeUI.closeWaiting()
			if (result['msg'] == '1') {
				mui.toast(tip+'成功')
				var nurSchAppList = plus.webview.getWebviewById('nurSchAppList')
				if (nurSchAppList) {
					nurSchAppList.evalJS('detailChanged()')
				}
				mui.back()
			}else{
				mui.toast(result['msg']+'失败')
			}
		}, function(errorStr) {
			mui.toast(errorStr)
			plus.nativeUI.closeWaiting()
		});
	}
	
	function getSaveParams(status){
		var date = $('#date')[0].innerText
		var sch = $('#sch')[0].getAttribute('data-id')
		if (pageType == '意愿排班') {
			if (date == '请选择') {
				mui.toast('请选择排班日期')
				return 0
			}
			var wardID = $('#ward')[0].getAttribute('data-id')
			if (!wardID) {
				mui.toast('请选择病区')
				return 0
			}
			
			if (!sch) {
				mui.toast('请选择班次')
				return 0
			}
			var rw = ''
			if (sourceData) {
				rw = sourceData['rw']
			}
			//'PerDR|'护士Id'^WardDR|病区Id^WishDate|排班日期^PostDR|班次Id^Status|状态^Remark|备注^rw|^Id '
			var parr = 'PerDR|'+loginPerID+'^WardDR|'+wardID+'^WishDate|'+date+'^PostDR|'+sch+'^Status|'+status+'^Remark|'+$('#mark')[0].value+'^rw|'+rw;
			var data = {'parr':parr,'method':'web.INMArgComm:SaveWishArrange'}
			return data
		}
		if (pageType == '换班申请') {
			var date = $('#date')[0].innerText
			if (date == '请选择') {
				mui.toast('请选择申请日期')
				return 0
			}
			var sch = $('#sch')[0].getAttribute('data-id')
			if (!sch) {
				mui.toast('请选择申请班次')
				return 0
			}
			var otherdate = $('#otherdate')[0].innerText
			if (!otherdate) {
				mui.toast('请选择换班日期')
				return 0
			}
			var otherper = $('#otherper')[0].getAttribute('data-id')
			if (!otherper) {
				mui.toast('请选择换班对象')
				return 0
			}
			var othersch = $('#othersch')[0].getAttribute('data-id')
			if (!othersch) {
				mui.toast('请选择换班班次')
				return 0
			}
			//申请日期^申请人^申请班次^换班日期^换班对象^换班班次^Id
			var parr = date+'^'+loginPerID+'^'+sch+'^'+otherdate+'^'+otherper+'^'+othersch+'^';
			var data = {'parr':parr,'method':'web.INMArgComm:SaveExchangeApp'}
			return data
		}
		if (pageType == '改班申请') {
			if (date == '请选择') {
				mui.toast('请选择改班日期')
				return 0
			}
			if (!sch) {
				mui.toast('请选择改班班次')
				return 0
			}
			var wantSch = $('#wantsch')[0].getAttribute('data-id')
			if (!wantSch) {
				mui.toast('请选择期望班次')
				return 0
			}
			//改班班次Id^期望班次Id^Id
			var parr = sch+'^'+wantSch+'^';
			var data = {'parr':parr,'method':'web.INMArgComm:SaveChangeApp','nurseid':loginPerID}
			return data
		}
		
	}
	
	function getPatWards(btn){
		plus.nativeUI.showWaiting('获取病区列表')
		var pdict = {'nurseid':nurseid}
		var paramDict = {'method':'web.INMDataLimit:FindRoleWardList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			plus.nativeUI.closeWaiting()
			var wardArr = result['data']
			for (var i = 0; i < wardArr.length; i++) {
				wardArr[i]['text'] = wardArr[i]['WardDesc']
			}
			if (!userPicker) {
				userPicker = new $.PopPicker();
			}
			userPicker.setData(wardArr)
			userPicker.show(function(items){
				var dict = items[0]
				var dom = btn.querySelector('.midText')
				dom.classList.remove('noText')
				dom.innerHTML = dict['text'];
				dom.setAttribute('data-id',dict['rw'])
			});
		}, function(errorStr) {
			mui.toast('请重试')
			plus.nativeUI.closeWaiting()
		});
	}
	
	//选择日期
	function selectDate(btn,isOther){
		var _self = btn
		if(_self.picker) {
			_self.picker.show(function(rs) {
				var midText = _self.querySelector('.midText')
				midText.innerText = rs.text
				midText.classList.remove('noText')
				_self.picker.dispose();
				_self.picker = null;
				if (pageType == '意愿排班') {
					return
				}
				if (!isOther) {
					getPerSchData(rs.text);
				}
				var otherper = $('#otherper')[0];
				otherper.removeAttribute('data-id')
				otherper.innerText = '请选择'
				otherper.classList.add('noText')
				var othersch = $('#othersch')[0];
				othersch.removeAttribute('data-id')
				othersch.innerText = '请选择'
				othersch.classList.add('noText')
			});
		} else {
			var optionsJson = '{"type":"date"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				var midText = _self.querySelector('.midText')
				midText.innerText = rs.text
				midText.classList.remove('noText')
				_self.picker.dispose();
				_self.picker = null;
				if (pageType == '意愿排班') {
					return
				}
				if (!isOther) {
					getPerSchData(rs.text);
				}
				var otherper = $('#otherper')[0];
				if (otherper) {
					otherper.removeAttribute('data-id')
					otherper.innerText = '请选择'
					otherper.classList.add('noText')
				}
				var othersch = $('#othersch')[0];
				if (othersch) {
					othersch.removeAttribute('data-id')
					othersch.innerText = '请选择'
					othersch.classList.add('noText')
				}
				
			});
		}
	}
	//选择班次 意愿/期望排班
	function getPostList(btn){
		//parr 班次^病区^类型
		if(pageType == '意愿排班'){
			wardID = $('#ward')[0].getAttribute('data-id')
		}
		var pdict = {"start":0,'limit':1000,'parr':'^'+wardID+'^P'} //P:排班 H:休假 S:特殊
		var paramDict = {'method':'web.INMDBComm:FindWardWishPostList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			plus.nativeUI.closeWaiting()
			if (result['msgcode'] != '1') {
				mui.toast(result['msg'])
				return
			}
			var schArr = result['data']
			for (var i = 0; i < schArr.length; i++) {
				schArr[i]['text'] = schArr[i]['PostDesc']
			}
			if (!userPicker) {
				userPicker = new $.PopPicker();
			}
			userPicker.setData(schArr)
			userPicker.show(function(items){
				var dict = items[0]
				var dom = btn.querySelector('.midText')
				dom.innerHTML = dict['text'];
				dom.setAttribute('data-id',dict['rw'])
				dom.classList.remove('noText')
			});
		}, function(errorStr) {
			mui.toast('请重试')
			plus.nativeUI.closeWaiting()
		});
	}
	
	function getPerSchData(dateStr,perID){
		var pdict = {'perId':loginPerID,'date':dateStr,'appFlag':'1','appRet':''}
		if (perID) {
			pdict['perId'] = perID
		}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMArgComm:GetPerDayArgInfo','params':JSON.stringify(pdict),'type':'MethodNoFilter'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			var post = result['data']['Post']
			var schDom = $('#sch')[0]
			if (perID) {
				schDom = $('#othersch')[0]
			}
			if (!post) {
				schDom.innerText = ''
				schDom.removeAttribute('data-id')
				schDom.classList.add('noText')
				return
			}
			var html = ''
			var ids = ''
			for (var i = 0; i < post.length; i++) {
				var onePost = post[i]
				if (html != "") {
					html += '、'
					ids = ','
				}
				html +=onePost['PostDesc']
				ids += onePost['rw']
			}
			if (html != '') {
				schDom.innerHTML = html;
				schDom.setAttribute('data-id',ids)
				schDom.classList.remove('noText')
			}else{
				schDom.innerHTML = '请选择';
				schDom.removeAttribute('data-id')
				schDom.classList.add('noText')
			}
		}, function(errorStr) {
			var schDom = $('#sch')[0]
			if (perID) {
				schDom = $('#othersch')[0]
			}
			schDom.innerText = ''
			schDom.classList.add('noText')
			schDom.removeAttribute('data-id')
		});
	}
	
	function getExChangePerList(btn){
		var date = $('#otherdate')[0].innerText
		var pdict = {"date":date,'ward':wardID}
		var paramDict = {'method':'web.INMArgComm:GetDayArgNurseList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			plus.nativeUI.closeWaiting()
			if (result['msgcode'] != '1') {
				mui.toast(result['msg'])
				return
			}
			var perArr = result['data']
			for (var i = 0; i < perArr.length; i++) {
				perArr[i]['text'] = perArr[i]['PerName']
			}
			if (!userPicker) {
				userPicker = new $.PopPicker();
			}
			userPicker.setData(perArr)
			userPicker.show(function(items){
				var dict = items[0]
				if (!dict['text']) {
					return
				}
				
				var dom = btn.querySelector('.midText')
				dom.innerHTML = dict['text'];
				dom.setAttribute('data-id',dict['Per'])
				dom.classList.remove('noText')
				getPerSchData(date,dict['Per'])
			});
		}, function(errorStr) {
			mui.toast('请重试')
			plus.nativeUI.closeWaiting()
		});
	}
	
	function baseSetup(){
		var self = plus.webview.currentWebview()
		pageType = self.title
		sourceData = self.data
		perInfo = app.getState()
		wardID=perInfo['loginWardId']
		nurseid=perInfo['loginID']
		loginPerID = perInfo['loginPerID']
		$('.mui-title')[0].innerText = pageType
		fillHtml()
		mui('#container').on('tap','.oneLine',oneLineTapped)
		mui('body').on('tap','.saveBtn',saveOrCommit) 
		if (sourceData) {
			updateNewUI()
		}
		mui("body").on("input",'textarea', function() {
			var textStr = this.value
			if (textStr.length > 150) {
				this.value = textStr.substring(0,150)
			}
			var countDom = this.nextElementSibling.querySelector('span')
			countDom.innerHTML = this.value.length
		});
	}
	function updateNewUI(){
		var date = $('#date')[0]
		date.innerText = sourceData['WishDate']
		date.classList.remove('noText')
		var ward = $('#ward')[0]
		ward.innerText = sourceData['WardDesc']
		ward.setAttribute('data-id',sourceData['WardDR']);
		ward.classList.remove('noText')
		var sch = $('#sch')[0]
		sch.innerText = sourceData['PostDesc']
		sch.setAttribute('data-id',sourceData['PostDR'])
		sch.classList.remove('noText')
		$('#mark')[0].value = sourceData['Remark']
		$('#mark')[0].nextElementSibling.querySelector('span').innerHTML = sourceData['Remark'].length
	}
	
	function oneLineTapped(){
		if ($('#mark')[0]) {
			$('#mark')[0].blur()
		}
		var type = this.getAttribute('data-type')
		if (type == 'date') {
			if (this.parentNode.getAttribute('data-type') == 'other') {
				selectDate(this,true)
			}else{
				selectDate(this)
			}
		}else if (type == 'ward') {
			getPatWards(this)
		}else if (type == 'sch') {
			if (pageType == '意愿排班' && $('#ward')[0].innerText == '请选择') {
				mui.toast('请先选择病区')
				return
			}
			var showStr = pageType
			if (pageType != '意愿排班') {
				showStr = this.querySelector('.leftTip').innerText
			}
			plus.nativeUI.showWaiting('获取可选'+showStr)
			getPostList(this)
		}else if(type == 'autosch'){ //根据日期自动获取
			var dateStr = this.previousElementSibling.querySelector('.midText').innerText
			getPerSchData(dateStr)
		}else if (type == 'othersch') {
			var dateStr = $('#otherdate')[0].innerText
			if (dateStr == '请选择') {
				mui.toast('请先选择换班日期')
				return
			}
			var perStr = $('#otherper')[0].getAttribute('data-id')
			if (!perStr) {
				mui.toast('请先选择换班对象')
				return
			}
			getPerSchData(dateStr,perStr)
		}else if (type == 'otherper') {
			var dateStr = $('#otherdate')[0].innerText
			if (dateStr == '请选择') {
				mui.toast('请先选择换班日期')
				return
			}
			getExChangePerList(this)
		}
	}
	
	function fillHtml(){
		var html = ''
		switch (pageType){
			case '意愿排班':
				html = '<div class="oneLine" data-type="date"><div class="leftTip">排班日期</div><div id="date" class="midText noText mui-ellipsis">请选择</div>'+
						'<div class="rightIcon mui-icon mui-icon-arrowright"></div></div>'+
					'<div class="oneLine" data-type="ward"><div class="leftTip">病区</div><div id="ward" class="midText noText mui-ellipsis">请选择</div>'+
						'<div class="rightIcon mui-icon mui-icon-arrowright"></div></div>'+
					'<div class="oneLine" data-type="sch"><div class="leftTip">班次</div><div id="sch" class="midText noText mui-ellipsis">请选择</div>'+
						'<div class="rightIcon mui-icon mui-icon-arrowright"></div></div>'+
					'<div class="mui-input-row"><textarea id="mark" placeholder="请输入备注"></textarea><div class="length"><span>0</span>/150</div></div>'+
					'<div id="commitBtn" class="mui-btn mui-btn-primary saveBtn">保存并提交</div>'+
					'<div id="saveBtn" class="mui-btn mui-btn-primary saveBtn">保存</div>';
				break;
			case '换班申请':
				html = '<ul class="mui-table-view">'+
						'<li class="mui-table-view-cell oneLine" data-type="date">'+
							'<div class="leftTip">申请日期</div>'+
							'<div id="date" class="midText noText mui-ellipsis">请选择</div>'+
							'<div class="rightIcon mui-icon mui-icon-arrowright"></div></li>'+
						'<li class="mui-table-view-cell oneLine"data-type="autosch">'+
							'<div class="leftTip">申请班次</div>'+
							'<div id="sch" class="midText noText mui-ellipsis">请选择</div>'+
							'<div class="rightIcon mui-icon mui-icon-arrowright"></div></li></ul>'+
					'<ul class="mui-table-view" data-type="other">'+
						'<li class="mui-table-view-cell oneLine" data-type="date">'+
							'<div class="leftTip">换班日期</div>'+
							'<div id="otherdate" class="midText noText mui-ellipsis">请选择</div>'+
							'<div class="rightIcon mui-icon mui-icon-arrowright"></div></li>'+
						'<li class="mui-table-view-cell oneLine" data-type="otherper">'+
							'<div class="leftTip">换班对象</div>'+
							'<div id="otherper" class="midText noText mui-ellipsis">请选择</div>'+
							'<div class="rightIcon mui-icon mui-icon-arrowright"></div></li>'+
						'<li class="mui-table-view-cell oneLine" data-type="othersch">'+
							'<div class="leftTip">换班班次</div>'+
							'<div id="othersch" class="midText noText mui-ellipsis">请选择</div>'+
							'<div class="rightIcon mui-icon mui-icon-arrowright"></div></li></ul>'+
					'<div id="commitBtn" class="mui-btn mui-btn-primary saveBtn">提交</div>';
				break;
			case '改班申请':
				html = '<div class="oneLine" data-type="date"><div class="leftTip">改班日期</div><div id="date" class="midText noText mui-ellipsis">请选择</div>'+
						'<div class="rightIcon mui-icon mui-icon-arrowright"></div></div>'+
					'<div class="oneLine" data-type="autosch"><div class="leftTip">改班班次</div><div id="sch" class="midText noText mui-ellipsis">请选择</div>'+
						'<div class="rightIcon mui-icon mui-icon-arrowright"></div></div>'+
					'<div class="oneLine" data-type="sch"><div class="leftTip">期望班次</div><div id="wantsch" class="midText noText mui-ellipsis">请选择</div>'+
						'<div class="rightIcon mui-icon mui-icon-arrowright"></div></div>'+
					'<div id="commitBtn" class="mui-btn mui-btn-primary saveBtn">提交</div>';
				break;
			default:
				break;
		}
		if (html!="") {
			$('#container')[0].innerHTML = html
		}
	}
})(mui)